<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="queryData.query" placeholder="请输入查询" class="input-with-select" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" stripe border>
        <!-- prop用来指定渲染的字段 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" >
          <template slot-scope="scope">
            <el-switch
            v-model="scope.row.mg_state" @change="changUserStatus(scope.row)">
          </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" >
          <template slot-scope="scope">
             <el-button type="primary" icon="el-icon-edit" circle size="mini" @click="showEdit(scope.row)"></el-button>
             <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="removeUser(scope.row.id)"></el-button>
             <el-tooltip :enterable="false" class="item" effect="dark" content="分配角色" placement="top">
              <el-button type="warning" icon="el-icon-setting" circle size="mini" @click="setRoles(scope.row)"></el-button>
            </el-tooltip>
             
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryData.pagenum"
      :page-sizes="[2, 5, 10, 20]"
      :page-size="2"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-card>

    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="30%" @close="addUserClose">
     <!-- 主体内容 -->
     <el-form ref="addUserForm" :model="addUserForm" :rules="addUserRules" label-width="80px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
     </el-form>
     <!-- 尾部内容 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
  title="修改用户"
  :visible.sync="EditdialogVisible"
  width="30%">

    <!-- 主体内容 -->
        <el-form ref="editUserForm" :model="editUserForm" :rules="addUserRules" label-width="80px" @close="editUserClose">
            <el-form-item label="用户名称" prop="username">
              <el-input v-model="editUserForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editUserForm.email"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
              <el-input v-model="editUserForm.mobile"></el-input>
            </el-form-item>
        </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editForm">确 定</el-button>
      </span>
    </el-dialog>
  
  
    <!-- 分配角色对话框 -->
  <el-dialog
    title="分配角色"
    :visible.sync="rolesDialogVisible"
    width="30%">
    <div>
      <p>当前用户:{{userInfo.username}}</p>
      <p>当前角色:{{userInfo.role_name}}</p>
      <p>分配角色:
        <!-- v-model既可以设置选择值，又可以获取被选中值 -->
        <el-select v-model="selectRoleVal" placeholder="请选择">
        <el-option
          v-for="item in rolesList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id">
        </el-option>
      </el-select></p>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="rolesDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="subSetRoles">确 定</el-button>
    </span>
  </el-dialog>
  
  </div>

  
</template>



<script>
export default {
  data() {
    var checkEmail=(rules,value,callback)=>{
      var reg=/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
      if(reg.test(value)){return callback()} 
      callback(new Error('邮箱验证失败'))
    };
    var checkMobile=(rules,value,callback)=>{
      var reg=/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/ ;
      if(reg.test(value)){return callback()} 
      callback(new Error('电话验证失败'))
    };
    return {
      // 获取用户列表参数
      queryData:{
         query:'',
         pagenum:1,
         pagesize:2
      },
      userList:[],
      total:0,
      dialogVisible:false,//添加用户对话框显示标志
      EditdialogVisible:false,//修改用户对画框显示标志
      addUserForm:{
        username:'123',
        password:'123',
        email:'123@12.com',
        mobile:'13333333333'
      },
      editUserForm:{
         username:'',
        email:'',
        mobile:''
      },
      addUserRules:{
        username:[
           { required: true, message: '请输入用户名称', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password:[
           { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email:[
           { required: true, message: '请输入邮箱地址', trigger: 'blur' },
           {validator:checkEmail,trigger:'blur'}
        ],
        mobile:[
           { required: true, message: '请输入电话号码', trigger: 'blur' },
           {validator:checkMobile,trigger:'blur'}
           
        ]
      },
      // 分配角色显示
      rolesDialogVisible:false,
      userInfo:{},//用户信息
      rolesList:[], //角色列表
      selectRoleVal:''//选择分配角色值

    };
  },

  created() {
    this.getUserList();
  },

  methods: {
    async getUserList(){
     const {data:res}= await this.$axios.get('users',{params:this.queryData})
     if(res.meta.status!==200) return this.$message.error('获取数据失败');
     this.userList=res.data.users;
     this.total=res.data.total;
    
    },
    handleSizeChange(val){
    this.queryData.pagesize=val;
    this.getUserList();
    },
    handleCurrentChange(val){
    this.queryData.pagenum=val;
    this.getUserList();
    },
    // 当开关发生变化时触发
    async changUserStatus(userInfo)
    {
      const {data:res}=await this.$axios.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if(res.meta.status!==200)
      {
        this.$message.error('修改失败')
        userInfo.mg_state=!userInfo,mg_state;
        return;
      }
      this.$message.success('修改成功')
    },
    // 重置输入框
    addUserClose(){
      this.$refs.addUserForm.resetFields()
    },
    // 提交表单事件
    submitForm(){
     
      this.$refs.addUserForm.validate(async (flag,obj)=>{
         if(!flag) return;
         const {data:res}=await this.$axios.post('users',this.addUserForm)
         if(res.meta.status!=201)return this.$message.error(res.meta.msg)
         this.$message.success("创建成功")
           this.dialogVisible = false
           this.getUserList()
      })
    },
    //点击显示修改对话框
    async showEdit(row){
      
      const {data:res}=await this.$axios.get(`users/${row.id}`)
      if(res.meta.status!=200)return this.$message.error('数据获取失败')
      
      this.editUserForm=res.data
      this.EditdialogVisible=true;
    }, // 监听关闭修改用户对话框
    editUserClose(){
      this.$refs.editUserForm.resetFields()
    },
    editForm()
    {
      
      this.$refs.editUserForm.validate(async (flag)=>{
        if(flag)
        {
          const {data:res}=await this.$axios.put(`users/${this.editUserForm.id}`,this.editUserForm)
          
          if(res.meta.status!=200)return this.$message.error('修改失败')
          this.$message.success('修改成功')
          this.EditdialogVisible=false;
           this.getUserList()
        }
      })
    },
    removeUser(id){
      this.$confirm('此操作将永久删除该用户，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
          .then(async () => {
            const {data:res}=await this.$axios.delete(`users/${id}`)
            
            if(res.meta.status!=200) return this.$message.error('删除失败')
            this.$message.success('删除成功');
            this.getUserList()
          })
          .catch(action => {
            this.$message('已取消删除')
          });
    },
    //点击分配角色按钮
    async setRoles(row){
    this.userInfo=row
    this.rolesDialogVisible=true;
     const {data:res}=await this.$axios.get('roles')
        if(res.meta.status!=200)return this.$message.error('获取列表失败')
        this.rolesList=res.data;
    },
    // 提交分配角色
    async subSetRoles(){
      if(!this.selectRoleVal) return this.$message.error('未选择角色')
      const {data:res}=await this.$axios.put(`users/${this.userInfo.id}/role`,{rid:this.selectRoleVal})
      if(res.meta.status!=200) return this.$message.error('分配角色失败')
      this.$message.success('成功分配角色')
      this.getUserList();
      this.rolesDialogVisible=false;
    },
    // 监听分配角色关闭对话框
    closeSetRole(){
      this.selectRoleVal=''
    }
  }
};
</script>

<style scoped lang='less'>

</style>
